
# 2.5. 自动微分

# 2.5.1. 一个简单的例子
import torch

x = torch.arange(4.0)
x.requires_grad_(True)
print(x.grad)
# 默认是None

y = 2 * torch.dot(x, x)

# x.grad.zero_() # 梯度清零
y = x.sum()
y.backward()
print(x.grad)
# tensor([1., 1., 1., 1.])


# 2.5.2. 非标量变量的反向传播
x.grad.zero_() # 梯度清零,前提梯度不为none
y = x * x
y.sum().backward()
print(x.grad)
# 单独计算批量中每个样本的偏导数之和
# tensor([0., 2., 4., 6.])


# 2.5.3. 分离计算
x.grad.zero_()
y = x * x
u = y.detach()
z = u * x

z.sum().backward()
print(x.grad == u)
# tensor([True, True, True, True])


# 2.5.4. Python控制流的梯度计算
def f(a):
    b = a * 2
    while b.norm() < 1000:
        b = b * 2
    if b.sum() > 0:
        c = b
    else:
        c = 100 * b
    return c

a = torch.randn(size=(), requires_grad=True)
d = f(a)
d.backward()

print(a.grad == d / a)
# tensor(True)